import {getToken, setToken,removeToken} from '@/utils/auth'
import {getTokenData, getUserInfo} from '@/api/user'
import {constantRoutes, resetRouter} from '@/router'
// 数据
const state = {
  // token
  token: getToken() || null,
  // 用户信息
  userInfo: {},
  routes: constantRoutes
}

// 同步修改
const mutations = {
  // 修改token
  setToken(state, token) {
    state.token = token
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除token
  reToken(state) {
    state.token = null
    removeToken()
  },
  removeUserInfo() {
    state.userInfo = {}
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  }
}

// 异步修改
const actions ={
  // 登录逻辑
  async login (context, data) {
    // console.log(data);
    // 发送请求获取token数据
    const res = await getTokenData(data)
    // console.log(res);
    const token = res
    // 将token存入仓库
    context.commit('setToken', token)
    // 将token持久化到本地
    setToken(token)
  },
  // 设置用户信息
  async getUser(context) {
    const res = await getUserInfo()
    // console.log(res);
    // 通过mutataion存到仓库
    context.commit('setUserInfo', res)
    return res
  },
  // 退出登录
  logout(context) {
    context.commit('reToken')
    context.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}